﻿using Entitas;
using UnityEngine;

public sealed class CellSpaceSystem : IInitializeSystem, IExecuteSystem
{
    private readonly IViewService _viewService;

    public CellSpaceSystem(IViewService viewService)
    {
        _viewService = viewService;
    }
    
    public void Initialize()
    {
        CellSpace cellSpace = new CellSpace(new Vector2(GameDefine.WORLD_SIZEX, GameDefine.WORLD_SIZEZ),
            new Vector2Int(GameDefine.CELL_NUMX, GameDefine.CELL_NUMZ));
        Contexts.sharedInstance.game.SetCellSpace(cellSpace);
        _viewService.CreateCellSpaceView(Contexts.sharedInstance.game.cellSpaceEntity);
    }

    public void Execute()
    {
        var entities = Contexts.sharedInstance.game
            .GetGroup(GameMatcher.AllOf(GameMatcher.Transform)).GetEntities();

        CellSpace cellSpace = Contexts.sharedInstance.game.cellSpace.cellSpace;
        cellSpace.EmptyCells();
        foreach (var e in entities)
        {
            Vector3 pos = e.transform.position;
            cellSpace.UpdateEntity(e, pos);
        }
    }
}